package com.magicborrow.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.android.volley.toolbox.NetworkImageView;
import com.magicborrow.R;
import com.magicborrow.utils.UIHelper;
import com.magicborrow.utils.VolleyTool;
import com.nostra13.universalimageloader.core.ImageLoader;


import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by ghost on 15/6/24.
 */
public class BannerView extends RelativeLayout {


    //自动轮播的时间间隔
    private final static int TIME_INTERVAL = 5000;
    //自动轮播启用开关
    private  boolean isAutoPlay = true;
    //放圆点的View的list
    //private List<View> dotViewsList;
    //放圆点的View的list
    private List<View> dotViewsList;
    private ArrayList<View> views;
    private  double wh = 58.0 / 75.0;
    private View v;
    private ViewPager vp;

    private LinearLayout llDot;
    private BannerAdapter adapter;
    private OnPageClickListener onPageClickListener;

    public void setOnPageClickListener(OnPageClickListener onPageClickListener) {
        this.onPageClickListener = onPageClickListener;
    }

    public BannerView(Context context) {
        super(context);
        initView();
    }

    public BannerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public BannerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }


    private void initView() {
        v = LayoutInflater.from(getContext()).inflate(R.layout.banner_layout, null);
       // v.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (UIHelper.getScreenWidth(getContext()) / wh)));

        vp = (ViewPager) v.findViewById(R.id.banner_vp);

        llDot = (LinearLayout) v.findViewById(R.id.dotLayout);

        // llDot.removeView(ivNor);
        addView(v);
        //  initListener();

    }

    public void setWh(double wh) {
        this.wh = wh;
    }

    private void createHeader(ArrayList<String> urls) {
        views = new ArrayList<>();
        NetworkImageView imv;
        int i = 0;
        for (String s : urls) {

            imv = new NetworkImageView(getContext());
            imv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (UIHelper.getScreenWidth(getContext()) * wh)));
            imv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            // imv.setImageDrawable(getResources().getDrawable(R.drawable.appmain_home_img_defult));
            imv.setBackgroundColor(getResources().getColor(R.color.banner_bg));
            imv.setTag(i);
            imv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (onPageClickListener == null) {
                        return;
                    }
                    onPageClickListener.onPageClick((Integer) view.getTag());
                }
            });
            views.add(imv);

            imv.setImageUrl(s, VolleyTool.getImageLoader());
           // ImageLoader.getInstance().displayImage(s,imv);
            i++;

        }
        adapter = new BannerAdapter(views);
        vp.setAdapter(adapter);
        initDot();
        initListener();


    }

    private void initListener() {
        vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // Toast.makeText(getContext(),"ssssssss",Toast.LENGTH_SHORT).show();
                if (isAutoPlay && views.size() != 0) {
                    if (timer != null)
                        timer.cancel();
                    timer = new Timer();
                    //设置自动播放时间
                    timer.schedule(new MyTask(), TIME_INTERVAL, 1000);
                }
                for (int i = 0; i < dotViewsList.size(); i++) {
                    // tag = position;
                    if (i == vp.getCurrentItem()) {
                        // viewPager.getc
                        dotViewsList.get(vp.getCurrentItem()).setBackgroundResource(R.mipmap.dot_pre);
                    } else {
                        dotViewsList.get(i).setBackgroundResource(R.mipmap.dot_nor);
                    }
                }
            }

            @Override
            public void onPageSelected(int position) {
                // Toast.makeText(getContext(), "ssssssss", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

/*
        vp.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                Log.i("===============", "+====" + vp.getCurrentItem());
                if (onPageClickListener != null) {
                    onPageClickListener.onPageClick(vp.getCurrentItem());
                }
            }
        });
*/

    }

    public void setAutoPlay(boolean autoPlay) {
        isAutoPlay = autoPlay;
    }

    public int getCurrentItem() {
        return vp.getCurrentItem();
    }


    private void initDot() {


        llDot.removeAllViews();
        dotViewsList = new ArrayList<>();
        if (views.size() == 0) {
            return;
        }
        ImageView dotView = null;
        // 热点个数与图片相等
        for (int i = 0; i < views.size(); i++) {
            dotView = new ImageView(getContext());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.leftMargin = 4;
            params.rightMargin = 4;
            llDot.addView(dotView, params);
            dotViewsList.add(dotView);
        }
        for (int i = 0; i < dotViewsList.size(); i++) {
            // tag = position;
            if (i == vp.getCurrentItem()) {
                // viewPager.getc
                dotViewsList.get(vp.getCurrentItem()).setBackgroundResource(R.mipmap.dot_pre);
            } else {
                dotViewsList.get(i).setBackgroundResource(R.mipmap.dot_nor);
            }
        }

    }

    public void setUrls(ArrayList<String> urls) {
        createHeader(urls);
    }


    /**
     * 轮播图适配器
     */
    class BannerAdapter extends PagerAdapter {
        ArrayList<View> views;

        public BannerAdapter(ArrayList<View> views) {
            //super();
            this.views = views;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return super.getPageTitle(position);
        }

        @Override
        public int getCount() {
            return views.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(views.get(position));
//       super.destroyItem(container, position, object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(views.get(position));
            return views.get(position);
        }
    }

    /**
     * 时间计时器
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (isAutoPlay)
                vp.setCurrentItem((vp.getCurrentItem() + 1) % views.size());
        }
    };
    private Timer timer;

    class MyTask extends TimerTask {
        public void run() {
            handler.sendEmptyMessage(0);
        }
    }

    public interface OnPageClickListener {
        public void onPageClick(int position);
    }


}
